<?xml version="1.0" encoding="UTF-8" ?>
<!--

    Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
    under one or more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding copyright
    ownership. Camunda licenses this file to you under the Apache License,
    Version 2.0; you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.camunda.bpm.engine.impl.persistence.entity.HistoricTaskInstanceEntity">

  <!-- HISTORIC TASK INSTANCE INSERT -->

  <insert id="insertHistoricTaskInstanceEvent" parameterType="org.camunda.bpm.engine.impl.history.event.HistoricTaskInstanceEventEntity">
      insert into ${prefix}ACT_HI_TASKINST (
        ID_,
        PROC_DEF_KEY_,
        PROC_DEF_ID_,
        ROOT_PROC_INST_ID_,
        PROC_INST_ID_,
        EXECUTION_ID_,
        CASE_DEF_KEY_,
        CASE_DEF_ID_,
        CASE_INST_ID_,
        CASE_EXECUTION_ID_,
        ACT_INST_ID_,
        NAME_,
        PARENT_TASK_ID_,
        DESCRIPTION_,
        OWNER_,
        ASSIGNEE_,
        START_TIME_,
        END_TIME_,
        DURATION_,
        DELETE_REASON_,
        TASK_DEF_KEY_,
        PRIORITY_,
        DUE_DATE_,
        FOLLOW_UP_DATE_,
        TENANT_ID_,
        REMOVAL_TIME_
      ) values (
        #{id ,jdbcType=VARCHAR},
        #{processDefinitionKey, jdbcType=VARCHAR},
        #{processDefinitionId, jdbcType=VARCHAR},
        #{rootProcessInstanceId, jdbcType=VARCHAR},
        #{processInstanceId, jdbcType=VARCHAR},
        #{executionId, jdbcType=VARCHAR},
        #{caseDefinitionKey, jdbcType=VARCHAR},
        #{caseDefinitionId, jdbcType=VARCHAR},
        #{caseInstanceId, jdbcType=VARCHAR},
        #{caseExecutionId, jdbcType=VARCHAR},
        #{activityInstanceId, jdbcType=VARCHAR},
        #{name ,jdbcType=VARCHAR},
        #{parentTaskId ,jdbcType=VARCHAR},
        #{description ,jdbcType=VARCHAR},
        #{owner ,jdbcType=VARCHAR},
        #{assignee ,jdbcType=VARCHAR},
        #{startTime, jdbcType=TIMESTAMP},
        #{endTime, jdbcType=TIMESTAMP},
        #{durationInMillis ,jdbcType=BIGINT},
        #{deleteReason ,jdbcType=VARCHAR},
        #{taskDefinitionKey ,jdbcType=VARCHAR},
        #{priority, jdbcType=INTEGER},
        #{dueDate, jdbcType=TIMESTAMP},
        #{followUpDate, jdbcType=TIMESTAMP},
        #{tenantId, jdbcType=VARCHAR},
        #{removalTime, jdbcType=TIMESTAMP}
      )
  </insert>

  <!-- HISTORIC TASK INSTANCE UPDATE -->

  <update id="updateHistoricTaskInstanceEvent" parameterType="org.camunda.bpm.engine.impl.persistence.entity.HistoricTaskInstanceEntity">
    update ${prefix}ACT_HI_TASKINST set
      EXECUTION_ID_ = #{executionId, jdbcType=VARCHAR},
      PROC_DEF_KEY_ = #{processDefinitionKey, jdbcType=VARCHAR},
      PROC_DEF_ID_ = #{processDefinitionId, jdbcType=VARCHAR},
      NAME_ = #{name, jdbcType=VARCHAR},
      PARENT_TASK_ID_ = #{parentTaskId, jdbcType=VARCHAR},
      DESCRIPTION_ = #{description, jdbcType=VARCHAR},
      OWNER_ = #{owner, jdbcType=VARCHAR},
      ASSIGNEE_ = #{assignee, jdbcType=VARCHAR},
      DELETE_REASON_ = #{deleteReason ,jdbcType=VARCHAR},
      TASK_DEF_KEY_ = #{taskDefinitionKey ,jdbcType=VARCHAR},
      PRIORITY_ = #{priority, jdbcType=INTEGER},
      DUE_DATE_ = #{dueDate, jdbcType=TIMESTAMP},
      FOLLOW_UP_DATE_ = #{followUpDate, jdbcType=TIMESTAMP},
      CASE_INST_ID_ = #{caseInstanceId, jdbcType=VARCHAR},
      CASE_DEF_ID_ = #{caseDefinitionId, jdbcType=VARCHAR}
      <if test="endTime!=null">
        , END_TIME_ = #{endTime, jdbcType=TIMESTAMP}
        , DURATION_ = #{durationInMillis, jdbcType=BIGINT}
      </if>

    where ID_ = #{id, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricTaskInstancesByRootProcessInstanceId"
          parameterType="java.util.Map">
    update ${prefix}ACT_HI_TASKINST set
    REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}

    where ROOT_PROC_INST_ID_ = #{rootProcessInstanceId, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricTaskInstancesByRootProcessInstanceId_mssql"
          parameterType="java.util.Map">
    update RES set
    RES.REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
    FROM ${prefix}ACT_HI_TASKINST RES WITH (FORCESEEK)
    where RES.ROOT_PROC_INST_ID_ = #{rootProcessInstanceId, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricTaskInstancesByProcessInstanceId"
          parameterType="java.util.Map">
    update ${prefix}ACT_HI_TASKINST
      set REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
      where PROC_INST_ID_ = #{processInstanceId, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricTaskInstancesByProcessInstanceId_mssql"
          parameterType="java.util.Map">
    update RES set
    RES.REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
    FROM ${prefix}ACT_HI_TASKINST RES WITH (FORCESEEK)
      where RES.PROC_INST_ID_ = #{processInstanceId, jdbcType=VARCHAR}
  </update>

  <!-- HISTORIC TASK INSTANCE SELECT -->

  <select id="selectHistoricTaskInstanceEvent" parameterType="java.lang.String" resultMap="historicTaskInstanceResultMap">
    select HTI.START_TIME_ from ${prefix}ACT_HI_TASKINST HTI
    where HTI.ID_ = #{id, jdbcType=VARCHAR}
  </select>

  <!-- HISTORIC TASK INSTANCE DELETE -->

  <delete id="deleteHistoricTaskInstance" parameterType="org.camunda.bpm.engine.impl.persistence.entity.HistoricTaskInstanceEntity">
    delete from ${prefix}ACT_HI_TASKINST where ID_ = #{id}
  </delete>

  <delete id="deleteHistoricTaskInstanceByProcessInstanceIds">
    delete
    from ${prefix}ACT_HI_TASKINST
    where
      <bind name="listOfIds" value="list"/>
      <bind name="fieldName" value="'PROC_INST_ID_'"/>
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.applyInForPaginatedCollection"/>
  </delete>

  <delete id="deleteHistoricTaskInstanceByCaseInstanceIds">
    delete
    from ${prefix}ACT_HI_TASKINST
    where
      <bind name="listOfIds" value="list"/>
      <bind name="fieldName" value="'CASE_INST_ID_'"/>
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.applyInForPaginatedCollection"/>
  </delete>

  <sql id="andWhereMinuteInDateBetweenSql">
    <if test="parameter.minuteFrom != null and parameter.minuteTo != null">
      AND ${datepart1}<include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.periodUnitFunction"/>${datepart2}${date}${datepart3}
      between #{parameter.minuteFrom, jdbcType=INTEGER} and #{parameter.minuteTo, jdbcType=INTEGER}
    </if>
  </sql>

  <sql id="andWhereMinuteInDateBetweenSql_oracle">
    <if test="parameter.minuteFrom != null and parameter.minuteTo != null">
      AND ${datepart1}${date}${datepart2}<include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.periodUnitFunction"/>${datepart3}
      between #{parameter.minuteFrom, jdbcType=INTEGER} and #{parameter.minuteTo, jdbcType=INTEGER}
    </if>
  </sql>

  <delete id="deleteHistoricTaskInstancesByRemovalTime"
          parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    <bind name="date" value="'REMOVAL_TIME_'"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    delete ${limitBeforeWithoutOffset} from ${prefix}ACT_HI_TASKINST
    where REMOVAL_TIME_ &lt;= #{parameter.removalTime}
    <include refid="andWhereMinuteInDateBetweenSql"/>
    ${limitAfterWithoutOffset}
  </delete>

  <delete id="deleteHistoricTaskInstancesByRemovalTime_oracle"
          parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    <bind name="date" value="'REMOVAL_TIME_'"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    delete ${limitBeforeWithoutOffset} from ${prefix}ACT_HI_TASKINST
    where REMOVAL_TIME_ &lt;= #{parameter.removalTime}
    <include refid="andWhereMinuteInDateBetweenSql_oracle"/>
    ${limitAfterWithoutOffset}
  </delete>

  <delete id="deleteHistoricTaskInstancesByRemovalTime_postgres_or_db2"
          parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    <bind name="date" value="'REMOVAL_TIME_'"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    delete ${limitBeforeWithoutOffset} from ${prefix}ACT_HI_TASKINST
    where ID_ IN
      (SELECT ID_
       FROM ${prefix}ACT_HI_TASKINST
       WHERE REMOVAL_TIME_ &lt;= #{parameter.removalTime} <include refid="andWhereMinuteInDateBetweenSql"/>
       ${limitAfterWithoutOffset})
  </delete>

  <!-- HISTORIC TASK INSTANCE RESULT MAP -->

  <resultMap id="historicTaskInstanceResultMap" type="org.camunda.bpm.engine.impl.persistence.entity.HistoricTaskInstanceEntity">
    <id property="id" column="ID_" jdbcType="VARCHAR" />
    <result property="processDefinitionKey" column="PROC_DEF_KEY_" jdbcType="VARCHAR" />
    <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="VARCHAR" />
    <result property="rootProcessInstanceId" column="ROOT_PROC_INST_ID_" jdbcType="VARCHAR" />
    <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR" />
    <result property="executionId" column="EXECUTION_ID_" jdbcType="VARCHAR" />
    <result property="caseDefinitionKey" column="CASE_DEF_KEY_" jdbcType="VARCHAR" />
    <result property="caseDefinitionId" column="CASE_DEF_ID_" jdbcType="VARCHAR" />
    <result property="caseInstanceId" column="CASE_INST_ID_" jdbcType="VARCHAR" />
    <result property="caseExecutionId" column="CASE_EXECUTION_ID_" jdbcType="VARCHAR" />
    <result property="activityInstanceId" column="ACT_INST_ID_" jdbcType="VARCHAR" />
    <result property="name" column="NAME_" jdbcType="VARCHAR" />
    <result property="parentTaskId" column="PARENT_TASK_ID_" jdbcType="VARCHAR" />
    <result property="description" column="DESCRIPTION_" jdbcType="VARCHAR" />
    <result property="owner" column="OWNER_" jdbcType="VARCHAR" />
    <result property="assignee" column="ASSIGNEE_" jdbcType="VARCHAR" />
    <result property="startTime" column="START_TIME_" jdbcType="TIMESTAMP" />
    <result property="endTime" column="END_TIME_" jdbcType="TIMESTAMP" />
    <result property="durationInMillis" column="DURATION_" jdbcType="BIGINT" />
    <result property="deleteReason" column="DELETE_REASON_" jdbcType="VARCHAR" />
    <result property="taskDefinitionKey" column="TASK_DEF_KEY_" jdbcType="VARCHAR" />
    <result property="priority" column="PRIORITY_" jdbcType="INTEGER" />
    <result property="dueDate" column="DUE_DATE_" jdbcType="TIMESTAMP" />
    <result property="followUpDate" column="FOLLOW_UP_DATE_" jdbcType="TIMESTAMP" />
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR" />
    <result property="removalTime" column="REMOVAL_TIME_" jdbcType="TIMESTAMP"/>
  </resultMap>

  <!-- HISTORIC TASK INSTANCE SELECT -->

  <select id="selectHistoricTaskInstance" resultMap="historicTaskInstanceResultMap">
    select * from ${prefix}ACT_HI_TASKINST where ID_ = #{historicTaskInstanceId}
  </select>

  <select id="selectHistoricTaskInstancesByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.HistoricTaskInstanceQueryImpl" resultMap="historicTaskInstanceResultMap">
  	<include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    select ${distinct} RES.*
    ${limitBetween}
    <include refid="selectHistoricTaskInstancesByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectHistoricTaskInstanceCountByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.HistoricTaskInstanceQueryImpl" resultType="long">
    ${countDistinctBeforeStart} RES.ID_ ${countDistinctBeforeEnd}
    <include refid="selectHistoricTaskInstancesByQueryCriteriaSql"/>
    ${countDistinctAfterEnd}
  </select>

  <sql id="selectHistoricTaskInstancesByQueryCriteriaSql">

    from ${prefix}ACT_HI_TASKINST RES

    <if test="authCheck.shouldPerformAuthorizatioCheck &amp;&amp; !authCheck.revokeAuthorizationCheckEnabled &amp;&amp; authCheck.authUserId != null">
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.authCheckJoinWithoutOnClause" />
      AUTH ON (AUTH.RESOURCE_ID_ ${authJoinStart}
        RES.PROC_DEF_KEY_ ${authJoinSeparator} '*'
        <if test="authCheck.isHistoricInstancePermissionsEnabled">
          ${authJoinSeparator} RES.PROC_INST_ID_
          ${authJoinSeparator} RES.ID_
        </if>
        ${authJoinEnd}
      )
    </if>

    <bind name="HPI_JOIN" value="false" />
    <bind name="D_JOIN" value="false" />
    <bind name="CD_JOIN" value="false" />
    <bind name="JOIN_TYPE" value="'inner join'" />

    <foreach collection="queries" item="query">
      <if test="query.isOrQueryActive">
        <bind name="JOIN_TYPE" value="'left join'" />
      </if>
      <if test="query != null &amp;&amp; (query.processFinished || query.processUnfinished || query.processInstanceBusinessKey != null || query.processInstanceBusinessKeyLike != null ||
              (query.processInstanceBusinessKeys != null &amp;&amp; query.processInstanceBusinessKeys.length > 0))">
        <bind name="HPI_JOIN" value="true" />
      </if>
      <if test="query != null &amp;&amp; (query.processDefinitionKey != null || query.processDefinitionName != null)">
        <bind name="D_JOIN" value="true" />
      </if>
      <if test="query != null &amp;&amp; (query.caseDefinitionKey != null || query.caseDefinitionName != null)">
        <bind name="CD_JOIN" value="true" />
      </if>
    </foreach>

    <if test="HPI_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_HI_PROCINST HPI ON RES.PROC_INST_ID_ = HPI.ID_
    </if>
    <if test="D_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_RE_PROCDEF D on RES.PROC_DEF_ID_ = D.ID_
    </if>
    <if test="CD_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_RE_CASE_DEF CD on RES.CASE_DEF_ID_ = CD.ID_
    </if>
    <where>
      <foreach collection="queries" item="query" index="i">
        <choose>
          <when test="i == 0">
            <bind name="queryType" value="'and'" />
          </when>
          <otherwise>
            <bind name="queryType" value="'or'" />
          </otherwise>
        </choose>
        and (
        <trim suffixOverrides="and">
          1 = 1 and
          <trim prefixOverrides="or|and">
            <if test="query.taskInvolvedUser != null || query.taskInvolvedGroup != null || query.taskHadCandidateUser != null || query.taskHadCandidateGroup != null || query.withCandidateGroups">
              ${queryType} RES.ID_ in (select TASK_ID_ from ${prefix}ACT_HI_IDENTITYLINK HIL
              <where>
                <if test= "query.taskInvolvedUser != null">
                  ${queryType} HIL.USER_ID_ = #{query.taskInvolvedUser}
                </if>
                <if test ="query.taskInvolvedGroup != null">
                  ${queryType} HIL.GROUP_ID_ = #{query.taskInvolvedGroup}
                </if>
                <if test="query.taskHadCandidateUser != null">
                  ${queryType} HIL.TYPE_ = 'candidate' and HIL.USER_ID_ = #{query.taskHadCandidateUser}
                </if>
                <if test="query.taskHadCandidateGroup != null">
                  ${queryType} HIL.TYPE_ = 'candidate' and HIL.GROUP_ID_ = #{query.taskHadCandidateGroup}
                </if>
                <if test="query.withCandidateGroups">
                  ${queryType} HIL.TYPE_ = 'candidate' and HIL.GROUP_ID_ is not null
                </if>
              </where>
              )
            </if>

            <if test="query.withoutCandidateGroups">
              ${queryType} not exists (
              select 1
              from
              ${prefix}ACT_HI_IDENTITYLINK HIL
              <where>
                HIL.TYPE_ = 'candidate' and HIL.GROUP_ID_ is not null
              </where>
              AND HIL.TASK_ID_ = RES.ID_
              )
            </if>

            <if test="query.taskId != null">
              ${queryType} RES.ID_ = #{query.taskId}
            </if>
            <if test="query.processDefinitionId != null">
              ${queryType} RES.PROC_DEF_ID_ = #{query.processDefinitionId}
            </if>
            <if test="query.processDefinitionKey != null">
              ${queryType} D.KEY_ = #{query.processDefinitionKey}
            </if>
            <if test="query.processDefinitionName != null">
              ${queryType} D.NAME_ = #{query.processDefinitionName}
            </if>
            <if test="query.processInstanceId != null">
              ${queryType} RES.PROC_INST_ID_ = #{query.processInstanceId}
            </if>
            <if test="query.processInstanceBusinessKey != null">
              ${queryType} HPI.BUSINESS_KEY_ = #{query.processInstanceBusinessKey}
            </if>
            <if test="query.processInstanceBusinessKeys != null &amp;&amp; query.processInstanceBusinessKeys.length > 0">
              ${queryType} HPI.BUSINESS_KEY_ in
              <foreach item="item" index="index" collection="query.processInstanceBusinessKeys"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.processInstanceBusinessKeyLike != null">
              ${queryType} HPI.BUSINESS_KEY_ like #{query.processInstanceBusinessKeyLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.taskDefinitionKeys != null &amp;&amp; query.taskDefinitionKeys.length > 0">
              ${queryType} RES.TASK_DEF_KEY_ in
              <foreach item="taskDefinitionKey" index="index" collection="query.taskDefinitionKeys"
                       open="(" separator="," close=")">
                #{taskDefinitionKey}
              </foreach>
            </if>
            <if test="query.executionId != null">
              ${queryType} RES.EXECUTION_ID_ = #{query.executionId}
            </if>
            <if test="query.activityInstanceIds != null &amp;&amp; query.activityInstanceIds.length > 0">
              ${queryType} RES.ACT_INST_ID_ in
              <foreach item="item" index="index" collection="query.activityInstanceIds"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.caseDefinitionId != null">
              ${queryType} RES.CASE_DEF_ID_ = #{query.caseDefinitionId}
            </if>
            <if test="query.caseDefinitionKey != null">
              ${queryType} CD.KEY_ = #{query.caseDefinitionKey}
            </if>
            <if test="query.caseDefinitionName != null">
              ${queryType} CD.NAME_ = #{query.caseDefinitionName}
            </if>
            <if test="query.caseInstanceId != null">
              ${queryType} RES.CASE_INST_ID_ = #{query.caseInstanceId}
            </if>
            <if test="query.caseExecutionId != null">
              ${queryType} RES.CASE_EXECUTION_ID_ = #{query.caseExecutionId}
            </if>
            <if test="query.taskName != null">
              <!-- CAM-12186 case insensitive task name and description queries -->
              ${queryType} UPPER(RES.NAME_) = UPPER(#{query.taskName})
            </if>
            <if test="query.taskNameLike != null">
              ${queryType} UPPER(RES.NAME_) like UPPER(#{query.taskNameLike}) ESCAPE ${escapeChar}
            </if>
            <if test="query.taskParentTaskId != null">
              ${queryType} RES.PARENT_TASK_ID_ = #{query.taskParentTaskId}
            </if>
            <if test="query.taskDescription != null">
              ${queryType} UPPER(RES.DESCRIPTION_) = UPPER(#{query.taskDescription})
            </if>
            <if test="query.taskDescriptionLike != null">
              ${queryType} UPPER(RES.DESCRIPTION_) like UPPER(#{query.taskDescriptionLike}) ESCAPE ${escapeChar}
            </if>
            <if test="query.taskDeleteReason != null">
              ${queryType} RES.DELETE_REASON_ = #{query.taskDeleteReason}
            </if>
            <if test="query.taskDeleteReasonLike != null">
              ${queryType} RES.DELETE_REASON_ like #{query.taskDeleteReasonLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.taskOwner != null">
              ${queryType} RES.OWNER_ = #{query.taskOwner}
            </if>
            <if test="query.taskOwnerLike != null">
              ${queryType} RES.OWNER_ like #{query.taskOwnerLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.assigned">
              ${queryType} RES.ASSIGNEE_ is not null
            </if>
            <if test="query.unassigned">
              ${queryType} RES.ASSIGNEE_ is null
            </if>
            <if test="query.taskAssignee != null">
              ${queryType} RES.ASSIGNEE_ = #{query.taskAssignee}
            </if>
            <if test="query.taskAssigneeLike != null">
              ${queryType} RES.ASSIGNEE_ like #{query.taskAssigneeLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.taskPriority != null">
              ${queryType} RES.PRIORITY_ = #{query.taskPriority}
            </if>
            <if test="query.unfinished">
              ${queryType} RES.END_TIME_ is null
            </if>
            <if test="query.finished">
              ${queryType} RES.END_TIME_ is not null
            </if>
            <if test="query.processFinished">
              ${queryType} HPI.END_TIME_ is not null
            </if>
            <if test="query.processUnfinished">
              ${queryType} HPI.END_TIME_ is null
            </if>
            <if test="query.startedAfter != null">
              ${queryType} RES.START_TIME_ &gt;= #{query.startedAfter}
            </if>
            <if test="query.startedBefore != null">
              ${queryType} RES.START_TIME_ &lt;= #{query.startedBefore}
            </if>
            <if test="query.finishedBefore != null">
              ${queryType} RES.END_TIME_ &lt;= #{query.finishedBefore}
            </if>
            <if test="query.finishedAfter != null">
              ${queryType} RES.END_TIME_ &gt;= #{query.finishedAfter}
            </if>
            <if test="query.dueDate != null || query.dueBefore != null || query.dueAfter != null">
              ${queryType}
              <trim prefix="(" suffix=")" prefixOverrides="and|or">
                <if test="query.dueDate != null">
                  ${queryType} RES.DUE_DATE_ = #{query.dueDate}
                </if>
                <if test="query.dueBefore != null">
                  ${queryType} RES.DUE_DATE_ &lt; #{query.dueBefore}
                </if>
                <if test="query.dueAfter != null">
                  ${queryType} RES.DUE_DATE_ &gt; #{query.dueAfter}
                </if>

                and RES.DUE_DATE_ is not null
              </trim>
            </if>
            <if test="query.withoutTaskDueDate">
              ${queryType} RES.DUE_DATE_ is null
            </if>
            <if test="query.followUpDate != null || query.followUpBefore != null || query.followUpAfter != null">
              ${queryType}
              <trim prefix="(" suffix=")" prefixOverrides="and|or">
                <if test="query.followUpDate != null">
                  ${queryType} RES.FOLLOW_UP_DATE_ = #{query.followUpDate}
                </if>
                <if test="query.followUpBefore != null">
                  ${queryType} RES.FOLLOW_UP_DATE_ &lt; #{query.followUpBefore}
                </if>
                <if test="query.followUpAfter != null">
                  ${queryType} RES.FOLLOW_UP_DATE_ &gt; #{query.followUpAfter}
                </if>

                and RES.FOLLOW_UP_DATE_ is not null
              </trim>
            </if>
            <if test="query.isTenantIdSet">
              <if test="query.tenantIds != null &amp;&amp; query.tenantIds.length > 0">
                ${queryType} RES.TENANT_ID_ in
                <foreach item="tenantId" index="index" collection="query.tenantIds"
                         open="(" separator="," close=")">
                  #{tenantId}
                </foreach>
              </if>
              <if test="query.tenantIds == null">
                ${queryType} RES.TENANT_ID_ is null
              </if>
            </if>
            <foreach collection="query.variables" index="index" item="queryVariableValue">
              ${queryType} exists (
                select
                  ID_
                from
                  ${prefix}ACT_HI_VARINST VAR
                WHERE
                <bind name="varPrefix" value="''"/>

                <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.variableNameEqualsCaseInsensitive" />

                <choose>
                  <when test="queryVariableValue.local">
                    and TASK_ID_ = RES.ID_
                  </when>
                  <otherwise>
                    and PROC_INST_ID_ = RES.PROC_INST_ID_ and TASK_ID_ is null
                  </otherwise>
                </choose>

              <bind name="varTypeField" value="'VAR_TYPE_'"/>
              <if test="queryVariableValue.valueConditions != null">
                and
                <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.variableValueConditions"/>
              </if>
              )
            </foreach>
          </trim>
        </trim>
        )
      </foreach>

      <if test="authCheck.shouldPerformAuthorizatioCheck &amp;&amp; authCheck.authUserId != null">
        <choose>
          <when test="authCheck.isHistoricInstancePermissionsEnabled">
            <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.queryAuthorizationCheck"/>
          </when>
          <otherwise>
            and (
              (RES.EXECUTION_ID_ is not null
              <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.queryAuthorizationCheck"/>
              )
              <!-- Auth check is skipped for standalone tasks -->
              or RES.EXECUTION_ID_ is null
            )
          </otherwise>
        </choose>
      </if>

      <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheck" />

    </where>
  </sql>

  <select id="selectHistoricTaskInstanceByNativeQuery" parameterType="java.util.Map" resultMap="historicTaskInstanceResultMap">
    <if test="resultType == 'LIST_PAGE'">
      ${limitBefore}
    </if>
    ${sql}
    <if test="resultType == 'LIST_PAGE'">
      ${limitAfter}
    </if>
  </select>

  <select id="selectHistoricTaskInstanceByNativeQuery_mssql_or_db2" parameterType="java.util.Map" resultMap="historicTaskInstanceResultMap">
    <if test="resultType == 'LIST_PAGE'">
        ${limitBeforeNativeQuery}
    </if>
    ${sql}
    <if test="resultType == 'LIST_PAGE'">
      ${limitAfter}
    </if>
  </select>

  <select id="selectHistoricTaskInstanceCountByNativeQuery" parameterType="java.util.Map" resultType="long">
    ${sql}
  </select>

  <select id="selectCompletedHistoricTaskInstancePage" resultMap="historicTaskInstanceResultMap" parameterType="java.util.Map" >
    <bind name="maxResults" value="parameter.maxResults" />

    ${optimizeLimitBeforeWithoutOffset}
    select ${limitBeforeWithoutOffset} * from ${prefix}ACT_HI_TASKINST RES

    <where>
      <if test="parameter.finishedAfter != null">
        and RES.END_TIME_ &gt; #{parameter.finishedAfter}
      </if>
      <if test="parameter.finishedAt != null">
        and RES.END_TIME_ = #{parameter.finishedAt}
      </if>
      <if test="parameter.finishedAfter == null and parameter.finishedAt == null">
        and RES.END_TIME_ is not null
      </if>
    </where>

    ORDER BY RES.END_TIME_ ASC
    ${optimizeLimitAfterWithoutOffset}
  </select>

  <select id="selectRunningHistoricTaskInstancePage" resultMap="historicTaskInstanceResultMap"
          parameterType="java.util.Map">
    <bind name="maxResults" value="parameter.maxResults"/>
    ${optimizeLimitBeforeWithoutOffset}
    select ${limitBeforeWithoutOffset} * from ${prefix}ACT_HI_TASKINST RES

    <where>
      <if test="parameter.startedAfter != null">
        and RES.START_TIME_ &gt; #{parameter.startedAfter}
      </if>
      <if test="parameter.startedAt != null">
        and RES.START_TIME_ = #{parameter.startedAt}
      </if>
      and RES.END_TIME_ is null
    </where>

    ORDER BY RES.START_TIME_ ASC
    ${optimizeLimitAfterWithoutOffset}
  </select>

</mapper>
